import { Component, OnInit } from '@angular/core';

import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { SetofkeyService } from "../../../../service/setofkey.service";
import { FormBuilder, Validators, FormControl } from "@angular/forms";
import { Command } from "../../../../shared/toolbar.service";
import { Observable } from "rxjs/Observable";
import { BladeData } from "../../../../shared/blade/blade-data";
import { MatrixStateGroup } from "../../../../entity/matrix-state-group.model";

import { MatrixLogicGroup } from "../../../../entity/matrix-logic-group.model";
import { MatrixLogicGroupService } from "../../../../service/matrix-logic-group.service"

@Component({
	selector: 'app-matrix-logic-group-edit',
	templateUrl: './matrix-logic-group-edit.component.html',
	styleUrls: ['./matrix-logic-group-edit.component.css']
})
export class MatrixLogicGroupEditComponent extends BladeContainerBase<MatrixLogicGroup> {

	public matrixLogicGroups: MatrixLogicGroup[] = [];
	public original: MatrixLogicGroup[] = [];

	constructor(
		private fb: FormBuilder,
		private matrixLogicGroupService: MatrixLogicGroupService) {
		super(fb)
	}

	ngOnInit() {
		//编辑时注册按钮和按钮命令    
		if (!this.isNew) {
			this.commands = [
				new Command("save", "保存", "fa fa-save", "setofkey:update", (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
				new Command("reset", "重置", "fa fa-save", "setofkey:reset", (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
			]
		}
		else {
			this.currentEntity = new MatrixLogicGroup(0, 0, '', true)
		}
		super.ngOnInit();
    }
    
    /**
    * 初始化数据
    * 
    * 
    * @memberof BladeContainerBase
    */
    initData(): any | Observable<any> | Promise<any> {
        if (this.parentBlade.parentBlade.parentEntity != null) {
			this.currentEntity.stateGroupId = (this.parentBlade.parentBlade.parentEntity as MatrixStateGroup).stateGroupId;
		}
        this.formPatchValue(this.currentEntity);
    }

	exeSaveChange(blade: any): void {
		this.saveChange();
	}
	canSaveChange(blade: any): boolean {
		return this.hasChange() && !this.hasError();
	}
	exeReset(blade: any): void {
		return this.formGroup.reset(this.currentEntity);
	}
	canReset(blade: any): boolean {
		return this.hasChange();
	}

    /**
    * 创建表单
    * 
    * 
    * @memberof DicKeyEditComponent
    */
    createForm() {
        this.formGroup = this.fromBuider.group({
            "logicGroupName": [this.currentEntity.logicGroupName, [
                Validators.required,
                Validators.maxLength(20),
            ], (control: FormControl): any => this.logicGroupNameAsnyValidator(control)],    
        });
    }

    /**
    * 设置表单错误对象
    * 
    * 
    * @memberof BladeContainerBase
    */
    setFormError(): void {
        this.formErrors = {        
            'logicGroupName': '',
        };
    }
    /**
    * 设置表单验证信息
    * 
    * 
    * @memberof BladeContainerBase
    */
    setValidationMessages(): void {
        this.validationMessages = {
            'logicGroupName': {
                'required': '状态组名称不能为空。',
                'maxlength': '名称不能多于20个字符长度。',
                'exist': '名称已存在',
            },
        };
    }

    /**
     * 异步校验Name是否存在
     * 
     * @param {FormControl} control 
     * @returns {Promise<true>} 
     * 
     * @memberof FarmEditComponent
     */
    logicGroupNameAsnyValidator(control: FormControl): any {
        return this.matrixLogicGroupService.hasLogicGroupName(control.value, this.currentEntity.logicGroupId, this.currentEntity.stateGroupId)
            .map(res => res ? { exist: true } : null);
    }

    /**
     * 创建
     * 
     * 
     * @memberof DicKeyEditComponent
     */
    onCreate() {
        if (!this.hasError()) {
            this.bladeData.isLoading = true;
            let formValue = this.formGroup.value;
            this.currentEntity.logicGroupName = formValue.logicGroupName;
            this.matrixLogicGroupService.create(this.currentEntity)
                .then(res => {
                    if (res) {
                        let parentContainerInstance = this.parentBlade.bladeContainerInstance;
                        parentContainerInstance.refresh(res);
                        this.bladeService.closeBlade(this.currentBlade);
                    }
                })
                .catch(error => this.bladeData.error = error)
                .then(res => this.bladeData.isLoading = false);
        }
    }

    saveChange(): any | Promise<any> | Observable<any> {
        if (this.canSaveChange(this.currentBlade)) {
            this.bladeData.isLoading = true;
            let formValue = this.formGroup.value;      
            this.currentEntity.logicGroupName = formValue.logicGroupName;
            return this.matrixLogicGroupService.update(this.currentEntity)
                .then(res => {
                    if (res) {
                        (this.parentBlade.bladeContainerInstance).refresh(res);
                        this.bladeService.closeBlade(this.currentBlade);
                        return true;
                    }
                })
                .catch(error => this.bladeData.error = error)
                .then(res => this.bladeData.isLoading = false);
        }
    }


}



// WEBPACK FOOTER //
// ./src/app/module/basic/matrix-config/matrix-logic-group-edit/matrix-logic-group-edit.component.ts